<template>
  <div class="content">
    <van-popup v-model:show="topshow" position="top" round :style="{}">
      <van-form @submit="onSubmitShop">
        <van-cell-group inset>
          <van-field v-model="shopInfo.s_name" name="s_name" label="店铺名称" :placeholder="shopInfo.s_name"
            :rules="[{ required: true, message: '请填写店铺名称' }]" />
          <van-field name="s_status" label="营业">
            <template #input>
              <van-switch v-model="sstatus" size="20" />
            </template>
          </van-field>
          <van-field v-model="shopInfo.s_owner" name="s_owner" label="店主人" :placeholder="shopInfo.s_owner"
            :rules="[{ required: true, message: '请填写店主人' }]" />
          <van-field v-model="shopInfo.s_create_time" name="s_create_time" label="注册时间" disabled
            :placeholder="shopInfo.s_create_time" :rules="[{ required: true, message: '形如:2022-06-27' }]" />
          <van-field v-model="shopInfo.s_introduction" name="s_introduction" label="店铺简介" autosize type="textarea"
            :placeholder="shopInfo.s_introduction" :rules="[{ required: true, message: '请填写店铺简介' }]" />
          <div style="display:flex;">
            <van-image width="4rem" height="4rem" fit="cover" style="position:relative;left:2rem;"
              :src="shopInfo.s_picture" />
            <label for="file" style="position:relative;left:10rem;top:2rem;display: flex; background-color: rgb(79, 152, 122);color:#fff;
              align-items: center; height: 2rem;border-radius: 0.5rem;">
              上传店铺图片
            </label>
            <input type="file" id="file" class="sr-only" accept="image/png,image/jpeg,image/jpg"
              @change="uploadImage($event.target.files)" style="display: none;" />
          </div>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </van-popup>
    <div class="top">
      <van-image width="100%" height="6rem" fit="cover" :src="shopInfo.s_picture" />
    </div>
    <div class="arrow" @click="onClickLeft">
      <van-icon name="arrow-left" />
    </div>
    <div class="center" @click="topshow = true">
      <div class="pic">
        <van-image width="3rem" height="3rem" fit="cover" :src="shopInfo.s_picture" />
      </div>
      <div class="first">
        <div class="name">{{ shopInfo.s_name }}</div>
        <div class="status">{{ shopInfo.s_status == 1 ? '营业中' : '休息' }}</div>
        <div class="sixcode">{{ sixcode }}</div>
      </div>
      <div class="second">
        <div class="comment">{{ shopInfo.s_comment }}分</div>
        <div class="owner">店主:{{ shopInfo.s_owner }}</div>
        <div class="time">自{{ shopInfo.s_create_time }}</div>
      </div>
      <div class="third">
        <div class="van-ellipsis introduction">{{ shopInfo.s_introduction }}</div>
      </div>
    </div>
    <div class="main">
      <div class="siderbar" ref="container">
        <van-sticky :offset-top="0" :container="container">
          <van-sidebar v-model="active" @change="onChange">
            <van-sidebar-item v-for="item in siderbarList" :title="item.title"
              :badge="item.count == 0 ? '' : item.count" />
          </van-sidebar>
        </van-sticky>
      </div>
      <div class="right_content">
        <van-index-bar :index-list="indexList" ref="siderbar">
          <div v-for="item in siderbarList">
            <van-index-anchor :index="item.title">{{ item.title }}</van-index-anchor>
            <div v-for="(item1, index1) in item.commodity" @click="modifyMeal(item1, index1)">
              <lazy-component>
                <van-card :price="(item1.mprice * 1).toFixed(2)" :desc="item1.mintro" :title="item1.mname"
                  :thumb="item1.mpic" :lazy-load="true">
                  <template #tags>
                    <van-tag plain type="danger">月销{{ item1.msales }}</van-tag>
                    <van-tag plain type="warning">库存{{ item1.mstock }}</van-tag>
                  </template>
                  <template #footer>
                    <van-tag type="danger" @click="deleteMeal(item1.mid, item.title)">删除</van-tag>
                  </template>
                </van-card>
              </lazy-component>
            </div>
          </div>
        </van-index-bar>
      </div>
    </div>
    <div class="bbb">
      <van-submit-bar button-text="上架餐品" @submit="onSubmit">
        <div style="display:flex;justify-content: center;align-items: center;position: relative;left: -8rem;"
          @click="backToC">
          <div>切换到顾客</div>
          <van-icon name="revoke" size="2rem" />
        </div>
      </van-submit-bar>
    </div>
    <van-popup v-model:show="bottomshow" position="bottom" round :style="{}">
      <van-form @submit="onSubmitAdd">
        <van-cell-group inset>
          <van-field v-model="newMeal.mname" name="mname" label="菜品名称" placeholder="请填写菜品名称"
            :rules="[{ required: true, message: '请填写菜品名称' }]" />
          <van-field v-model="newMeal.mintro" name="mintro" label="菜品介绍" placeholder="请填写菜品介绍" autosize type="textarea"
            :rules="[{ required: true, message: '请填写菜品介绍' }]" />
          <van-grid square clickable :border="true" column-num="5" style="width: 100%;">
            <van-grid-item v-for="i in indexLists" :key="i" :text="i" @click="newMeal.mtype = i" />
          </van-grid>
          <van-field v-model="newMeal.mtype" name="mtype" label="菜品种类" placeholder="请选择菜品种类"
            :rules="[{ required: true, message: '请选择菜品种类' }]" />

          <van-field v-model="newMeal.mstock" name="mstock" label="菜品库存" placeholder="请填写菜品库存"
            :rules="[{ required: true, message: '请填写菜品库存' }]" />
          <van-field v-model="newMeal.mprice" name="mprice" label="菜品单价" placeholder="请填写菜品单价"
            :rules="[{ required: true, message: '请填写菜品单价' }]" />
          <div style="display:flex;">
            <van-image width="4rem" height="4rem" fit="cover" style="position:relative;left:2rem;" :src="newMealLink" />
            <label for="file" style="position:relative;left:10rem;top:2rem;display: flex; background-color: rgb(79, 152, 122);color:#fff;
              align-items: center; height: 2rem;border-radius: 0.5rem;">
              上传餐品图片
            </label>
            <input type="file" id="file" class="sr-only" accept="image/png,image/jpeg,image/jpg"
              @change="uploadImage($event.target.files)" style="display: none;" />
          </div>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            上架
          </van-button>
        </div>
      </van-form>
    </van-popup>
    <!-- 修改餐品pop -->
    <van-popup v-model:show="middleshow" round :style="{ width: '100%' }">
      <van-form @submit="onSubmitModify">
        <van-cell-group inset>
          <van-field v-model="readyToModify.mname" name="mname" label="菜品名称" placeholder="请填写菜品名称"
            :rules="[{ required: true, message: '请填写菜品名称' }]" />
          <van-field v-model="readyToModify.mintro" name="mintro" label="菜品介绍" placeholder="请填写菜品介绍"
            :rules="[{ required: true, message: '请填写菜品介绍' }]" />
          <van-grid square clickable :border="true" column-num="5" style="width: 100%;">
            <van-grid-item v-for="i in indexLists" :key="i" :text="i" @click="readyToModify.mtype = i" />
          </van-grid>
          <van-field v-model="readyToModify.mtype" name="mtype" label="菜品种类" placeholder="请选择菜品种类"
            :rules="[{ required: true, message: '请选择菜品种类' }]" />

          <van-field v-model="readyToModify.mstock" name="mstock" label="菜品库存" placeholder="请填写菜品库存"
            :rules="[{ required: true, message: '请填写菜品库存' }]" />
          <van-field v-model="readyToModify.mprice" name="mprice" label="菜品单价" placeholder="请填写菜品单价"
            :rules="[{ required: true, message: '请填写菜品单价' }]" />
          <div style="display:flex;">
            <van-image width="4rem" height="4rem" fit="cover" style="position:relative;left:2rem;"
              :src="readyToModify.mpic" />
            <label for="file" style="position:relative;left:10rem;top:2rem;display: flex; background-color: rgb(79, 152, 122);color:#fff;
              align-items: center; height: 2rem;border-radius: 0.5rem;">
              修改餐品图片
            </label>
            <input type="file" id="file" class="sr-only" accept="image/png,image/jpeg,image/jpg"
              @change="uploadImage($event.target.files)" style="display: none;" />
          </div>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            确认修改
          </van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { getCurrentInstance } from '@vue/runtime-core';
import { useRouter } from 'vue-router'
const request = require('@/network/request').default;
import { dateFormat } from '@/utils/time'
import bus from 'vue3-eventbus'
import { useStore } from 'vuex'
import { uploadFile } from "@/utils/upload";
import { ImgUrl } from '../../constant.ts'

export default {
  name: 'HandleShop',
  props: [],
  setup(props, context) {
    const active = ref(0);
    const onClickLeft = () => history.back();
    const shopInfo = ref([]);
    const siderbarList = ref([]);
    const indexList = ref([]);
    const indexLists = ref([])
    const index = ref(0)
    const show = ref(false);
    const topshow = ref(false)
    const bottomshow = ref(false)
    const middleshow = ref(false)
    const sstatus = ref()
    const overlayshow = ref(false)
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const container = ref(null);
    const link = ref('')
    const newMealLink = ref('')
    const sid = ref('')
    const showPopover = ref(false)
    const readyToModify = ref({})
    const sixcode = ref('')
    const backToC = () => {
      bus.emit('isShop', { isShop: false })
      let info = JSON.parse(localStorage.getItem('userInfo'))
      info.type = 1
      localStorage.setItem('userInfo', JSON.stringify(info))
      router.push('/user')
    }
    const onSelect = (action) => {
      // console.log(action)
      newMeal.value.mtype = action.text
    };
    const store = useStore()
    const newMeal = ref({
      mname: '',
      mintro: '',
      msales: '',
      mstock: '',
      mtype: '',
      mprice: ''
    })
    bus.emit('routerInfo', { active: router.currentRoute._value.name })
    watch(shopInfo, (newValue, oldValue) => {
      sstatus.value = shopInfo.value.s_status == 1 ? true : false
    })
    onMounted(function () {
      let shop = {
        suid: JSON.parse(localStorage.getItem('userInfo')).uid
      }
      request.post('/getsidbyuid', shop.suid).then(res => {
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0) {
          // console.log(res)
          sid.value = res.data
        }
      })
      if (store.getters['shopercart/getshopInfo'].s_name) {
        getData()
      }
      else {
        request.post('/getcodebyuid', shop).then(res => {
          if (res.code == -1) {
            console.log(res)
          } else if (res.code == 0) {
            // console.log(res)
            sixcode.value = res.data
            findShop(res.data)
          }
        })
      }
    })
    onUnmounted(() => {
      saveData()
    })
    function saveData() {
      store.commit('shopercart/saveshopInfo', shopInfo.value)
      store.commit('shopercart/savesiderbarList', siderbarList.value)
    }
    function getData() {
      shopInfo.value = store.getters['shopercart/getshopInfo']
      siderbarList.value = store.getters['shopercart/getsiderbarList']
    }
    function findShop(sixcode) {
      let shop = {
        ssixcode: sixcode
      }
      request.post('/getshop', shop).then(res => {
        console.log(res)
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0) {
          shopInfo.value = {
            s_name: res.data.sname,
            s_create_time: res.data.screatetime,
            s_picture: res.data.spicture,
            s_comment: res.data.scomment,
            s_introduction: res.data.sintroduction,
            s_status: res.data.sstatus,
            s_owner: res.data.sowner
          }
          findMeal(res.data.sid)
        }
      })
    }
    function findMeal(msid) {
      let meal = {
        msid: msid
      }
      request.post('/getmeal', meal).then(res => {
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0 && res.data.length > 0) {
          let oldVa = res.data[0].mtype
          let oldarr = []
          res.data.forEach((item, index) => {
            if (item.mtype != oldVa) {
              siderbarList.value.push({
                title: oldVa,
                count: 0,
                commodity: oldarr
              })
              oldarr = []
            }
            if (index == res.data.length - 1 && item.mtype == oldVa) {
              oldarr.push(item)
              siderbarList.value.push({
                title: oldVa,
                count: 0,
                commodity: oldarr
              })
              oldarr = []
            }
            if (index == res.data.length - 1 && item.mtype != oldVa) {
              oldarr.push(item)
              siderbarList.value.push({
                title: item.mtype,
                count: 0,
                commodity: oldarr
              })
              oldarr = []
            }
            oldarr.push(item)
            oldVa = item.mtype
          })
          indexLists.value = []
          siderbarList.value.forEach(item => {
            indexLists.value.push(item.title)
          })
        }
      })
    }

    const onChange = (index1) => {
      currentInstance.ctx.$refs.siderbar.scrollTo(indexLists.value[index1])
    };
    const deleteMeal = (mid, title) => {
      console.log(mid, title)
      request.post('/deletemeal', mid).then(res => {
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0) {
          siderbarList.value.forEach((item1, index1) => {
            if (item1.title == title) {
              item1.commodity.forEach((item2, index2) => {
                if (item2.mid == mid) {
                  item1.commodity.splice(index2, 1)
                  if (item1.commodity.length == 0) {
                    siderbarList.value.splice(index1, 1)
                  }
                }
              })
            }
          });
        }
      })
    }
    function uploadImage(files) {
      console.log(files)
      if (files.length > 0) {
        uploadFile(files[0]).subscribe({
          next: (result) => {
            console.log(result)
          },
          error: (err) => {
            console.log(err)
          },
          complete: (e) => {
            link.value = ImgUrl + e.key
            console.log(link.value)
            let shop = {
              sowner: shopInfo.value.s_owner,
              spicture: link.value
            }
            if (topshow) {
              request.post('/updatespic', shop).then(res => {
                if (res.code == -1) {
                  console.log(res)
                } else if (res.code == 0) {
                  console.log(res)
                  shopInfo.value.s_picture = link.value
                  // topshow.value = false
                }
              })
            }
            if (bottomshow) {
              newMealLink.value = link.value
            }
            if (middleshow) {
              readyToModify.value.mpic = link.value
            }
          },
        });
      }
    }
    const onSubmitShop = (values) => {
      // console.log(values)
      let shop = {
        sowner: values.s_owner,
        screatetime: values.s_create_time,
        sintroduction: values.s_introduction,
        sname: values.s_name,
        sstatus: values.s_status == true ? 1 : 0
      }
      request.post('/updatesinfo', shop).then(res => {
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0) {
          shopInfo.value = {
            s_name: res.data.sname,
            s_create_time: res.data.screatetime,
            s_picture: res.data.spicture,
            s_comment: res.data.scomment,
            s_introduction: res.data.sintroduction,
            s_status: res.data.sstatus,
            s_owner: res.data.sowner,
          }
          topshow.value = false
        }
      })
    }
    const onSubmitAdd = (values) => {
      // console.log(values)
      let meal = {
        mname: values.mname,
        mintro: values.mintro,
        mpic: newMealLink.value,
        mprice: (Number(values.mprice) * 1).toFixed(2),
        mstock: values.mstock,
        msales: 0,
        mtype: values.mtype,
        mstatus: 1,
        msid: sid.value
      }
      // console.log(meal)
      request.post('/insertmeal', meal).then(res => {
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0) {
          console.log(res)
          newMeal.value = []
          siderbarList.value = []
          findMeal(sid.value)
          bottomshow.value = false
        }
      })
    }
    const modifyMeal = (item) => {
      console.log(item)
      readyToModify.value = item
      middleshow.value = true
    }
    const onSubmitModify = (values) => {
      // console.log(values)
      let meal = {
        mid: readyToModify.value.mid,
        mname: values.mname,
        mintro: values.mintro,
        mpic: readyToModify.value.mpic,
        mprice: (Number(values.mprice) * 1).toFixed(2),
        mstock: values.mstock,
        msales: 0,
        mtype: values.mtype,
        mstatus: 1,
        msid: sid.value
      }
      // console.log(meal)
      request.post('/modifymeal', meal).then(res => {
        if (res.code == -1) {
          console.log(res)
        } else if (res.code == 0) {
          // console.log(res)
          siderbarList.value = []
          findMeal(sid.value)
          middleshow.value = false
        }
      })
    }
    const onSubmit = () => {
      bottomshow.value = true
    }
    return {
      active,
      shopInfo,
      onClickLeft,
      siderbarList,
      indexList,
      onChange,
      index,
      onSubmit,
      show,
      overlayshow,
      currentInstance,
      container,
      topshow,
      bottomshow,
      sstatus,
      onSubmitShop,
      uploadImage,
      deleteMeal,
      onSubmitAdd,
      newMeal,
      newMealLink,
      showPopover,
      onSelect,
      indexLists,
      middleshow,
      onSubmitModify,
      modifyMeal,
      readyToModify,
      backToC,
      sixcode
    };
  },
}
</script>

<style scoped lang="scss">
.content {
  height: 100%;
  background-color: rgb(240, 236, 236);

  .arrow {
    position: absolute;
    color: #fff;
    top: 1rem;
    left: 0.5rem;
    font-size: larger;
  }

  .center {
    width: 20rem;
    height: 5.6rem;
    border-radius: 0.8rem;
    position: relative;
    top: -2.8rem;
    margin: 0 auto;
    background-color: #fff;

    // padding: 5px;
    .pic {
      position: absolute;
      height: 50%;
      right: 0.8rem;
      top: 0.8rem;
      border-radius: 0.3rem;
      overflow: hidden;
    }

    .first {
      display: flex;
      position: relative;

      .name {
        font-size: 18px;
        padding: 8px 12px 0 12px;
        font-weight: bold;
      }

      .status {
        color: #fff;
        background-color: rgb(42, 176, 230);
        border-radius: 8px;
        align-self: center;
        padding: 0 2px 0 2px;
        font-size: 12px;
        margin-top: 8px;
      }

      .sixcode {
        position: absolute;
        right: 5rem;
        top: 0.8rem;
        font-weight: bold;
      }
    }

    .second {
      display: flex;

      .comment {
        color: rgb(232, 116, 23);
        font-size: 10px;
        font-weight: bold;
        padding: 5px 0 5px 12px;
      }

      .owner {
        color: rgb(167, 152, 140);
        font-size: 10px;
        font-weight: bold;
        padding: 5px 0 5px 12px;
      }

      .time {
        color: rgb(167, 152, 140);
        font-size: 10px;
        font-weight: bold;
        padding: 5px 0 5px 12px;
      }
    }

    .third {
      .introduction {
        font-size: small;
        padding: 3px 0 5px 12px;
        color: rgb(137, 135, 135);
      }
    }
  }

  .main {
    position: relative;
    display: flex;
    width: 100%;
    top: -2.7rem;

    .siderbar {
      width: 21%;
      position: sticky;
      top: 3rem;
      height: 85vh;
    }

    .right_content {
      width: 78%;
      position: relative;
      left: 1%;
      // top: -18rem;
    }
  }

  .bottom {
    position: relative;
    top: -2.7rem;

    .text {
      position: absolute;
      font-weight: bold;
      bottom: 5rem;
      left: 50%;
      transform: translate(-50%);
    }
  }

  .bbb {

    .badge {
      position: absolute;
      bottom: 2.5rem;
      right: 3rem;
    }
  }

  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .block {
      // width: 120px;
      // height: 120px;
      // background-color: #fff;
      color: #fff;
    }
  }

}
</style>